<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>动态选项表格助手</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    
    <style>
        body {
            background-color: #f8f9fa;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        .main-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .upload-area {
            border: 2px dashed #007bff;
            border-radius: 10px;
            padding: 40px;
            text-align: center;
            background-color: white;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        .upload-area:hover {
            background-color: #f8f9fa;
            border-color: #0056b3;
        }
        .upload-area.dragover {
            background-color: #e3f2fd;
            border-color: #2196f3;
        }
        .filter-section {
            background-color: white;
            border-radius: 10px;
            padding: 20px;
            margin-top: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .column-filter {
            margin-bottom: 15px;
        }
        .column-name {
            font-weight: bold;
            margin-bottom: 5px;
            color: #495057;
        }
        .option-checkbox {
            margin-right: 10px;
            margin-bottom: 5px;
        }
        .preview-table {
            background-color: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }
        .spinner-border {
            width: 3rem;
            height: 3rem;
        }
        .btn-export {
            background-color: #28a745;
            border-color: #28a745;
        }
        .btn-export:hover {
            background-color: #218838;
            border-color: #1e7e34;
        }
        .select-all-btn {
            font-size: 0.8em;
            margin-left: 10px;
            cursor: pointer;
            color: #007bff;
        }
        .select-all-btn:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="main-container">
        <h1 class="text-center mb-4">
            <i class="fas fa-table"></i> 动态选项表格助手
        </h1>
        
        <!-- 文件上传区域 -->
        <div class="upload-area" id="uploadArea">
            <i class="fas fa-cloud-upload-alt fa-3x text-primary mb-3"></i>
            <h4>拖拽文件到此处或点击选择</h4>
            <p class="text-muted">支持 Excel (.xlsx, .xls) 和 CSV 文件</p>
            <input type="file" id="fileInput" accept=".xlsx,.xls,.csv" style="display: none;">
            <button class="btn btn-primary" onclick="document.getElementById('fileInput').click()">
                <i class="fas fa-folder-open"></i> 选择文件
            </button>
        </div>

        <!-- 加载指示器 -->
        <div class="loading" id="loading">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-2">正在处理文件...</p>
        </div>

        <!-- 筛选区域 -->
        <div id="filterSection" style="display: none;">
            <div class="filter-section">
                <h4><i class="fas fa-filter"></i> 筛选选项</h4>
                <p class="text-muted">根据列内容选择要导出的数据</p>
                <div id="filtersContainer"></div>
                <button class="btn btn-export" id="exportBtn" disabled>
                    <i class="fas fa-download"></i> 导出筛选后的数据
                </button>
            </div>
        </div>

        <!-- 数据预览 -->
        <div id="previewSection" style="display: none;">
            <h4 class="mt-4"><i class="fas fa-eye"></i> 数据预览</h4>
            <div class="preview-table">
                <div class="table-responsive">
                    <table class="table table-striped table-hover mb-0" id="previewTable">
                        <thead class="table-dark"></thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
    
    <script>
        let currentData = null;
        let currentFilename = null;

        // 文件上传处理
        const fileInput = document.getElementById('fileInput');
        const uploadArea = document.getElementById('uploadArea');
        const loading = document.getElementById('loading');
        const filterSection = document.getElementById('filterSection');
        const previewSection = document.getElementById('previewSection');

        // 拖拽上传
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });

        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                handleFile(files[0]);
            }
        });

        fileInput.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                handleFile(e.target.files[0]);
            }
        });

        function handleFile(file) {
            if (!file.name.match(/\.(xlsx|xls|csv)$/i)) {
                alert('请上传 Excel 或 CSV 文件！');
                return;
            }

            const formData = new FormData();
            formData.append('file', file);

            loading.style.display = 'block';
            uploadArea.style.display = 'none';

            fetch('/upload', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                loading.style.display = 'none';
                
                if (data.error) {
                    alert(data.error);
                    resetUploadArea();
                    return;
                }

                currentData = data;
                currentFilename = data.filename;
                
                displayFilters(data.columns, data.column_options);
                displayPreview(data.data_preview, data.columns);
                
                filterSection.style.display = 'block';
                previewSection.style.display = 'block';
            })
            .catch(error => {
                console.error('Error:', error);
                alert('上传失败，请重试！');
                resetUploadArea();
            });
        }

        function resetUploadArea() {
            loading.style.display = 'none';
            uploadArea.style.display = 'block';
            filterSection.style.display = 'none';
            previewSection.style.display = 'none';
            fileInput.value = '';
        }

        function displayFilters(columns, columnOptions) {
            const container = document.getElementById('filtersContainer');
            container.innerHTML = '';

            columns.forEach(column => {
                const options = columnOptions[column] || [];
                
                const filterDiv = document.createElement('div');
                filterDiv.className = 'column-filter';
                
                const columnHeader = document.createElement('div');
                columnHeader.className = 'column-name';
                columnHeader.innerHTML = `
                    ${column}
                    <span class="select-all-btn" onclick="toggleSelectAll('${column}')">全选/取消</span>
                `;
                
                const optionsDiv = document.createElement('div');
                optionsDiv.className = 'options-container';
                
                options.forEach(option => {
                    const label = document.createElement('label');
                    label.className = 'form-check form-check-inline';
                    label.innerHTML = `
                        <input type="checkbox" class="form-check-input option-checkbox" 
                               data-column="${column}" value="${option}">
                        <span class="form-check-label">${option}</span>
                    `;
                    optionsDiv.appendChild(label);
                });

                filterDiv.appendChild(columnHeader);
                filterDiv.appendChild(optionsDiv);
                container.appendChild(filterDiv);
            });

            document.getElementById('exportBtn').disabled = false;
        }

        function toggleSelectAll(column) {
            const checkboxes = document.querySelectorAll(`input[data-column="${column}"]`);
            const allChecked = Array.from(checkboxes).every(cb => cb.checked);
            
            checkboxes.forEach(checkbox => {
                checkbox.checked = !allChecked;
            });
        }

        function displayPreview(data, columns) {
            const table = document.getElementById('previewTable');
            const thead = table.querySelector('thead');
            const tbody = table.querySelector('tbody');

            // 清空表格
            thead.innerHTML = '';
            tbody.innerHTML = '';

            // 创建表头
            const headerRow = document.createElement('tr');
            columns.forEach(column => {
                const th = document.createElement('th');
                th.textContent = column;
                headerRow.appendChild(th);
            });
            thead.appendChild(headerRow);

            // 填充数据
            data.forEach(row => {
                const tr = document.createElement('tr');
                columns.forEach(column => {
                    const td = document.createElement('td');
                    td.textContent = row[column] || '';
                    tr.appendChild(td);
                });
                tbody.appendChild(tr);
            });
        }

        // 导出功能
        document.getElementById('exportBtn').addEventListener('click', () => {
            const filters = {};
            
            // 收集所有选中的筛选条件
            document.querySelectorAll('.option-checkbox:checked').forEach(checkbox => {
                const column = checkbox.dataset.column;
                const value = checkbox.value;
                
                if (!filters[column]) {
                    filters[column] = [];
                }
                filters[column].push(value);
            });

            const exportData = {
                filename: currentFilename,
                filters: filters
            };

            fetch('/export', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(exportData)
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(err => { throw err; });
                }
                return response.blob();
            })
            .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `filtered_${currentFilename}`;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
            })
            .catch(error => {
                console.error('Error:', error);
                alert(error.error || '导出失败，请重试！');
            });
        });
    </script>
</body>
</html>
